package com.cht.sys;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.cht.sys.to.OperationTO;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class CommonUtil {
	
	static private String url = "http://10.80.71.72:8056/UtilWeb/";
	
	public CommonUtil() {

		/*
		 * //取得連線的位址 Properties prop = new Properties(); InputStream ins = null;
		 * try { ins =
		 * LDAP.class.getResourceAsStream("/authorization.properties");
		 * prop.load(ins); url = prop.getProperty("url"); } catch (Exception e)
		 * { e.printStackTrace(); } finally { if (ins != null) { try {
		 * ins.close(); } catch (IOException e) { e.printStackTrace(); } } }
		 */
	}
	
	public static ArrayList getDutyList(String employeeno) throws JsonSyntaxException, Exception {
		String params = "?employeeno="+employeeno;
		return new Gson().fromJson(queryServlet("GetDutyList",params), new TypeToken<ArrayList>(){}.getType());
	}
	
	public static int setSendMail(Map MailMap) throws NumberFormatException, Exception {
		String params = "?MailMap="+new Gson().toJson(MailMap);
		return Integer.parseInt( queryServlet("SetSendMail",params) );
	}
	
	public static Set getUserByDuty(String duty) throws JsonSyntaxException, Exception {
		String params = "?duty="+duty;
		return new Gson().fromJson(queryServlet("GetUserByDuty",params), new TypeToken<Set>(){}.getType());
	}
	
	public static Set getUserNameSet(Set UserSet) throws JsonSyntaxException, Exception {
		String params = "?UserSet="+new Gson().toJson(UserSet);;
		String res = queryServlet("GetUserNameSet",params);
		if ( res.contains("Exception") ) {
			throw new Exception(res);
		}
		return new Gson().fromJson(res, new TypeToken<Set>(){}.getType());
	}
	
	public static boolean setUserAuth(String action,String userid,String username,String organization,Set dutylist) throws Exception {
		String params = "?action="+action+"&userid="+userid+"&username="+username+"&organization="+organization+"&dutylist="+new Gson().toJson(dutylist);;
		String res = queryServlet("SetUserAuth",params);
		if ( res.contains("Exception") ) {
			throw new Exception(res);
		}
		return Boolean.parseBoolean( res );
	}
	
	
	public static ArrayList getDutyList(String employeeno,String officecode) throws JsonSyntaxException, Exception {
		String params = "?employeeno="+employeeno+"&officecode="+officecode;
		return new Gson().fromJson(queryServlet("GetDutyList",params), new TypeToken<ArrayList>(){}.getType());
	}
	
	public static String getUnitName(String unitid,String topsJNDI) throws Exception {
		String params = "?unitid="+unitid+"&topsJNDI="+topsJNDI;
		return queryServlet("GetUnitName",params);
	}
	
	public static String getUserName(String UserID) throws Exception {
		String params = "?UserID="+UserID;
		return queryServlet("GetUserName",params);
	}
	
	public static String getTopsEmpInfo(String employeeno) throws Exception {
		String params = "?employeeno="+employeeno;
		return queryServlet("GetTopsEmpInfo",params);
	}
	
	public static String employeeExist(String employeeno) throws Exception {
		String params = "?employeeno="+employeeno;
		return queryServlet("EmployeeExist",params);
	}
	
	/*public static String chtDescramble(String input) throws Exception {
		String params = "?input="+input;
		return queryServlet("ChtDescramble",params);
	}
	
	public static String chtScramble(String input) throws Exception {
		String params = "?input="+input;
		return queryServlet("ChtScramble",params);
	}*/
	
	public static String chtDescramble(String input) throws Exception {
		return CommonUtil.chtDescramble(input);
	}
	
	public static String chtScramble(String input) throws Exception {
		return  CommonUtil.chtScramble(input);
	}
	
	public static String getYear() {
		return CommonUtil.getYear();
	}
	
	/**
	 * @param now	yyyy/MM/dd HH:mm:ss
	 */
	public static String genTraceSql(String oprCode,String operationCode,String sql,Date now)  throws Exception {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String params = "?oprCode="+oprCode+"&operationCode="+operationCode+"&sql="+sql+"&now="+formatter.format(now);
		return queryServlet("GenTraceSql",params);
	}
	
	public static String getOffice(String officecode) throws Exception {
		String params = "?officecode="+officecode;
		return queryServlet("GetOffice",params);
	}
	
	public static String getOffice(String officecode,String jndiname) throws Exception {
		String params = "?officecode="+officecode+"&jndiname"+jndiname;
		return queryServlet("GetOffice",params);
	}
	
	public static String getAlert() throws Exception {
		return queryServlet("GetAlert","");
	}
	
	public static List<OperationTO> getAllOperations() throws Exception {
		return new Gson().fromJson(queryServlet("GetAllOperations",""), new TypeToken<List<OperationTO>>(){}.getType());
	}
	
	public static List<OperationTO> getAllPermissions(String dutyStr) throws Exception {
		String params = "?dutyStr="+dutyStr;
		return new Gson().fromJson(queryServlet("GetAllPermissions",params), new TypeToken<List<OperationTO>>(){}.getType());
	}
	
	public static String getEmail(String employeeno) throws Exception {
		String params = "?employeeno="+employeeno;
		return queryServlet("GetEmailByAuthorization",params);
	}
	
	public static String getDepartment(String UserID) throws Exception {
		String params = "?UserID="+UserID;
		return queryServlet("GetDepartment",params);
	}
	
	public static String getDutyName(String dutycode) throws Exception {
		String params = "?dutycode="+dutycode;
		return queryServlet("GetDutyName",params);
	}

	public static int getDutyCount(String employeeno) throws Exception {
		String params = "?employeeno="+employeeno;
		return Integer.parseInt( queryServlet("GetDutyCount",params) );
	}
	
	public static String getOfficeCode2(String officecode) throws Exception {
		String params = "?officecode="+officecode;
		return queryServlet("GetOfficeCode2",params);
	}
	
	public static String getOfficeCode(String UserID) throws Exception {
		String params = "?UserID="+UserID;
		return queryServlet("GetOfficeCode",params);
	}
	public static String getOfficeCode(String UserID,char supp_flag) throws Exception {
		String params = "?UserID="+UserID+"&supp_flag="+supp_flag;
		return queryServlet("GetOfficeCode",params);
	}
	public static String getOfficeCode(String UserID,String SSO_sessionid) throws Exception {
		String params = "?UserID="+"&SSO_sessionid="+SSO_sessionid;
		return queryServlet("GetOfficeCode",params);
	}
	
	public static String hasAuth(String employeeno,String topsJNDI) throws Exception {
		String params = "?employeeno="+employeeno+"&topsJNDI="+topsJNDI;
		return queryServlet("HasAuth",params);
	}
	
	public static String getEmployee(String grantee,String colname) throws Exception {
		String params = "?grantee="+grantee+"&colname="+colname;
		return queryServlet("GetEmployee",params);
	}
	public static boolean getEmployeeIP(String employeeno,String clientIP) throws Exception {
		String params = "?employeeno="+employeeno+"&clientIP="+clientIP;
		String res = queryServlet("GetEmployeeIP",params);
		if ( res.contains("Exception") ) {
			throw new Exception(res);
		}
		return Boolean.parseBoolean( res );
	}
	public static ArrayList getGroupClassList(String duty) throws Exception {
		String params = "?duty="+duty;
		return new Gson().fromJson(queryServlet("GetGroupClassList",params), new TypeToken<ArrayList>(){}.getType());
	}
	
	public static String getEmployeeOrderUnit(String employeeno,String topsJNDI) throws Exception {
		String params = "?employeeno="+employeeno+"&topsJNDI="+topsJNDI;
		return queryServlet("GetEmployeeOrderUnit",params);
	}
	
	public static String isServiceCenter(String employeeno,String topsJNDI) throws Exception {
		String params = "?employeeno="+employeeno+"&topsJNDI="+topsJNDI;
		return queryServlet("IsServiceCenter",params);
	}
	
	public static String isSpecialServiceCenter(String serviceCenterID,String topsJNDI) throws Exception {
		String params = "?serviceCenterID="+serviceCenterID+"&topsJNDI="+topsJNDI;
		return queryServlet("IsSpecialServiceCenter",params);
	}
	public static boolean isUserInDuty(String employeeno,String s) throws Exception {
		String params = "?employeeno="+employeeno+"&s="+s;
		return Boolean.parseBoolean( queryServlet("IsUserInDuty",params) );
	}
	
	public static String getServiceCenterOrderUnit(String serviceCenterID,String topsJNDI) throws Exception {
		String params = "?serviceCenterID="+serviceCenterID+"&topsJNDI="+topsJNDI;
		return queryServlet("GetServiceCenterOrderUnit",params);
	}
	
	public static boolean isUserInRole(String employeeno,String s) throws Exception {
		String params = "?employeeno="+employeeno+"&s="+s;
		return Boolean.parseBoolean( queryServlet("IsUserInRole",params) );
	}
	
	public static boolean isUserInRole(String employeeno,String _group,String _class) throws Exception {
		String params = "?employeeno="+employeeno+"&_group="+_group+"&_class="+_class;
		return Boolean.parseBoolean( queryServlet("IsUserInRole",params) );
	}
	
	public static void loadSystemProperty() throws Exception {
		InputStream ins = null;
		String res = "";
		try {
			URL gwtServlet = new URL(url+"LoadSystemProperty");
			HttpURLConnection servletConnection = (HttpURLConnection) gwtServlet.openConnection();
			ins = servletConnection.getInputStream();
			if ( res.contains("Exception") ) {
				throw new Exception();
			}	
		} catch (Exception e) {
			throw e;
		} finally {
			if (ins != null) { try { ins.close(); } catch (IOException e) { e.printStackTrace(); } }
		}
	}
	
	public static String replaceXSSString(String in) throws Exception {
		String params = "?in="+in;
		return queryServlet("ReplaceXSSString",params);
	}
	
	public static int updateDutymembers(String topsEmpNo,String topsJNDI) throws Exception {
		String params = "?topsEmpNo="+topsEmpNo+"&topsJNDI="+topsJNDI;
		return Integer.parseInt( queryServlet("UpdateDutymembers",params) );
	}
	
	public static int updateEmployee(String employeeExist,String topsEmpNo,String topsEmpName,String topsEmpOffice) throws Exception {
		String params = "?employeeExist="+employeeExist+"&topsEmpNo="+topsEmpNo+"&topsEmpName="+topsEmpName+"&topsEmpOffice="+topsEmpOffice;
		return Integer.parseInt( queryServlet("UpdateEmployee",params) );
	}
	
	public static Calendar getCurrent(){
		return CommonUtil.getCurrent();
	}
	
	public static String getDate() {
		return CommonUtil.getDate();
	}
	public static Date getDate(int yyyy,int mm,int dd) {
		return CommonUtil.getDate(yyyy, mm, dd);
	}
	public static Date getDate(String yyyy,int mm,int dd) {
		return CommonUtil.getDate(yyyy, mm, dd);
	}
	public static Date getDate(String yyyy,int mm,String dd) {
		return CommonUtil.getDate(yyyy, mm, dd);
	}
	public static Date getDate(String yyyy,String mm,String dd) {
		return CommonUtil.getDate(yyyy, mm, dd);
	}
	public static Date getToday() {
		return CommonUtil.getToday();
	}
	public static java.sql.Date getTodaySQL() {
		return CommonUtil.getTodaySQL();
	}
	public static java.sql.Date getDateSQL(int yyyy,int mm,int dd) {
		return CommonUtil.getDateSQL(yyyy, mm, dd);
	}
	public static java.sql.Date getDateSQL(String yyyy,int mm,int dd) {
		return CommonUtil.getDateSQL(yyyy, mm, dd);
	}
	public static java.sql.Date getDateSQL(String yyyy,int mm,String dd) {
		return CommonUtil.getDateSQL(yyyy, mm, dd);
	}
	public static java.sql.Date getDateSQL(String yyyy,String mm,String dd) {
		return CommonUtil.getDateSQL(yyyy, mm, dd);
	}

	public static String getMonth() {
		return CommonUtil.getMonth();
	}
	
	public static void setLog4J(String level,String Log4JClass,String message) throws Exception {
		InputStream ins = null;
		String res = "";
		try {
			URL gwtServlet = new URL(url+"SetLog4J?level="+level+"&Log4JClass="+Log4JClass+"&message="+message);
			HttpURLConnection servletConnection = (HttpURLConnection) gwtServlet.openConnection();
			ins = servletConnection.getInputStream();
			if ( res.contains("Exception") ) {
				throw new Exception();
			}	
		} catch (Exception e) {
			throw e;
		} finally {
			if (ins != null) { try { ins.close(); } catch (IOException e) { e.printStackTrace(); } }
		}
	}
	
	private static String queryServlet(String method,String params) throws Exception {
		InputStream ins = null;
		String res = "";
		try {
			
			URL gwtServlet = new URL(url+method+params);
			HttpURLConnection servletConnection = (HttpURLConnection) gwtServlet.openConnection();
			ins = servletConnection.getInputStream();
			res = convertStreamToString(ins);
			if ( res.equalsIgnoreCase("") ) {
				res = null;	
			}	
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (ins != null) { try { ins.close(); } catch (IOException e) { e.printStackTrace(); } }
		}
		return res;
	}
	
	//轉換inputStream 為 字串
		private static String convertStreamToString(InputStream is) throws IOException {
			if (is != null) {
				Writer writer = new StringWriter();

				char[] buffer = new char[1024];
				try {
					Reader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
					int n;
					while ((n = reader.read(buffer)) != -1) {
						writer.write(buffer, 0, n);
					}
				} finally { is.close(); }
				return writer.toString();
			} else { return ""; }
		}
}
